package com.myapplication.zhou.alldemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.RecyclerView.OnScrollListener;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.myapplication.adapter.SearchPageRecycleViewAdapter;
import com.myapplication.callback.SearchByOrderCallback;
import com.myapplication.callback.SearchCallback;
import com.myapplication.interfaces.SearchInter;
import com.myapplication.interfaces.SearchPageConnect;
import com.myapplication.itemdecoration.DividerItemDecoration1;
import com.myapplication.model.Footer;
import com.myapplication.model.GoodsList;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class SearchPageActivity extends AppCompatActivity implements SearchCallback, SwipeRefreshLayout.OnRefreshListener, SearchByOrderCallback,
        View.OnClickListener, SearchPageRecycleViewAdapter.SearchClick {

    private SearchInter searchInter;
    @ViewInject(R.id.edit_text_search)
    private EditText edittextsearch;
    @ViewInject(R.id.textView_search)
    private TextView textViewsearch;
    @ViewInject(R.id.default_textView)
    private TextView defaulttextView;
    @ViewInject(R.id.price)
    private LinearLayout price;
    @ViewInject(R.id.sales)
    private LinearLayout sales;
    @ViewInject(R.id.shaixuan)
    private LinearLayout shaixuan;
    @ViewInject(R.id.recycleView1)
    private RecyclerView recycleView1;
    @ViewInject(R.id.textView_price)
    private TextView textView_price;
    @ViewInject(R.id.textview_sales)
    private TextView textView_sales;
    private SearchPageRecycleViewAdapter searchPageRecycleViewAdapter;
    private List<Object> searchList = new ArrayList<>();
    private String keyword;
    private int lastVisiblePosition = 0;
    private LinearLayoutManager layoutManager;
    private boolean hasmore;
    private int pageTotal;
    private String totalNumber;
    private int currentPage = 1;
    private Footer footer;
    @ViewInject(R.id.swipeRefresh)
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean states = false;
    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;
    private int key = 3;
    private int order;
    private String keyname = "gcc_id";
    private int clickdefault = -1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search_page);
        x.view().inject(this);
        searchInter = new SearchPageConnect();
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        searchPageRecycleViewAdapter = new SearchPageRecycleViewAdapter(this, searchList);
        recycleView1.addItemDecoration(new DividerItemDecoration1(this,
                DividerItemDecoration1.VERTICAL_LIST));
        recycleView1.setLayoutManager(layoutManager);
        recycleView1.setAdapter(searchPageRecycleViewAdapter);
        //  recycleView1.setNestedScrollingEnabled(false);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_orange_light, android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_red_light);
        Bundle bundle = getIntent().getExtras();
        keyword = bundle.getString("keyword");
        keyname = bundle.getString("keyname");
        if (keyname == null) {
            keyname = "gc_id";
        }
        Log.i("keyword", keyword);
        Log.i("keyname", keyname);
        swipeRefreshLayout.setOnRefreshListener(this);
        recycleView1.requestFocus();
        recycleView1.addOnScrollListener(onScroll);
        swipeRefreshPost();

        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        key = 2;

        defaulttextView.setOnClickListener(this);
        price.setOnClickListener(this);
        sales.setOnClickListener(this);
        textViewsearch.setOnClickListener(this);
        searchPageRecycleViewAdapter.setOnItemClick(this);
    }

    /**
     * item 点击事件
     *
     * @param v        layout
     * @param object   GoodsList
     * @param position layoutpostion
     */
    @Override
    public void onSearchClick(View v, Object object, int position) {

        GoodsList goodsList = (GoodsList) object;
        Intent intent = new Intent();

        Bundle bundle = new Bundle();
        bundle.putString("goods_id", goodsList.getGoods_id());
        intent.putExtras(bundle);
        if ("0".equals(goodsList.getIs_virtual())) {
            intent.setClass(this, GoodsInfoActivity.class);
        } else
            intent.setClass(this, GoodsInfoForVirtualActivity.class);

        startActivity(intent);
    }

    /**
     * 排序点击事件
     */
    @Override
    public void onClick(View v) {
        changeColor(v.getId());
        switch (v.getId()) {
            case R.id.default_textView:
                clickdefault = 1;
                swipeRefreshPost();
                currentPage = 1;
                httpRequest(keyword, keyname, 2, currentPage + "");
                break;
            case R.id.sales:
                clickdefault = 2;
                swipeRefreshPost();
                currentPage = 1;
                httpRequest(keyword, keyname, 1, currentPage + "");
                break;
            case R.id.price:
                swipeRefreshPost();
                currentPage = 1;
                if (clickdefault == 1 || clickdefault == 2 || clickdefault == -1) {
                    clickdefault = 3;
                    order = 2;
                } else if (clickdefault == 3) {
                    order = 1;
                    clickdefault = -1;
                }
                httpRequest(keyword, keyname, 3, order, currentPage + "");

        }
    }

    /**
     * 没有下拉时，让swipeRefreshLayout 旋转并更新
     */
    public void swipeRefreshPost() {
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                onRefresh();
            }
        });
    }

    /**
     * 排序时改变选中状态
     */
    public void changeColor(int id) {
        switch (id) {
            case R.id.default_textView:
                defaulttextView.setTextColor(getResources().getColor(R.color.colorAccent));
                textView_price.setTextColor(getResources().getColor(R.color.color_7d7d7d7));
                textView_sales.setTextColor(getResources().getColor(R.color.color_7d7d7d7));
                break;
            case R.id.price:
                textView_price.setTextColor(getResources().getColor(R.color.colorAccent));
                textView_sales.setTextColor(getResources().getColor(R.color.color_7d7d7d7));
                defaulttextView.setTextColor(getResources().getColor(R.color.color_7d7d7d7));
                break;
            case R.id.sales:
                textView_sales.setTextColor(getResources().getColor(R.color.colorAccent));
                defaulttextView.setTextColor(getResources().getColor(R.color.color_7d7d7d7));
                textView_price.setTextColor(getResources().getColor(R.color.color_7d7d7d7));
                break;
        }
    }

    /**
     * 滚动监听事件
     */
    OnScrollListener onScroll = new OnScrollListener() {
        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
            recycleViewOnScrollStates(newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
            lastVisiblePosition = layoutManager.findLastVisibleItemPosition();
            Log.i("skskskks", lastVisiblePosition + "");
           /* View lastChildView = recyclerView.getChildAt(recyclerView.
                    getLayoutManager().getChildCount() - 1);
            lastChildBottom = lastChildView.getBottom();
            recyclerBottom = recyclerView.getBottom() - recyclerView.getPaddingBottom();
            lastVisiblePosition = recyclerView.getLayoutManager().getPosition(lastChildView);*/

        }
    };

    /**
     * @param curPage 当前页面
     * @param keyword
     * @param key     when key:1 order by sales, when key:2 order by default
     */
    public void httpRequest(String keyword, String keyname, int key, String curPage) {

        searchInter.searchGoods(keyword, keyname, key + "", curPage, this);
    }

    /**
     * @param key   when key 3 order by price
     * @param order 1 降序 ,2 升序
     */

    public void httpRequest(String keyword, String keyname, int key, int order, String curPage) {
        searchInter.searchGoodsByOrder(keyword, keyname, key + "", curPage + "", order + "", this);


    }

    /**
     * 滑动时间监听
     */
    public void recycleViewOnScrollStates(int newStates) {
        if (searchList.size() == 0)
            Snackbar.make(textViewsearch, "没有找到奥！", Snackbar.LENGTH_SHORT).show();
        if (newStates == RecyclerView.SCROLL_STATE_IDLE && lastVisiblePosition + 1 == recycleView1.getLayoutManager().getItemCount()) {
            //curpage<=totalPage
            if (currentPage == pageTotal) {
                Snackbar.make(textViewsearch, "没有下一页了", Snackbar.LENGTH_SHORT).show();
            } else if (!states && currentPage < pageTotal) {
                states = true;
                onPreLoad();

            }

        }
    }

    private void onPreLoad() {
        if (footer != null) {
            searchList.remove(footer);
        }
        footer = new Footer();
        footer.setText("正在加载中......");
        searchList.add(footer);
        searchPageRecycleViewAdapter.notifyDataSetChanged();
        onLoad();
    }

    private void onLoad() {
        currentPage++;
        Log.i("jsjsjjs", keyword);
        if (key == 1)
            httpRequest(keyword, keyname, 1, currentPage + "");
        if (key == 2)
            httpRequest(keyword, keyname, 2, currentPage + "");
        if (key == 3) {
            httpRequest(keyword, keyname, 3, order, currentPage + "");
        }
    }

    @Override
    public void onSearchSuccess(String searchSuccess) {
        Log.i("jsjjs", searchSuccess);
        if (footer != null)
            searchList.remove(footer);
        phareJsonDataforGoodList(searchSuccess);
    }


    @Override
    public void onSearchFail(String searchFail) {

    }

    public void phareJsonDataforGoodList(String json) {
        List<Object> searchLists = new ArrayList<>();
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
        try {
            Gson gson = new Gson();
            JSONObject jsonObject = new JSONObject(json);
            pageTotal = jsonObject.optInt("page_total");
            hasmore = jsonObject.optBoolean("hasmore");
            totalNumber = jsonObject.optString("total_num");
            JSONObject jsonObject1 = jsonObject.optJSONObject("datas");
            String strJsonArray = jsonObject1.optJSONArray("goods_list").toString();
            Type type = new TypeToken<List<GoodsList>>() {
            }.getType();
            searchLists = gson.fromJson(strJsonArray, type);

        } catch (JSONException e) {
            e.printStackTrace();
        }

        searchList.addAll(searchLists);
        searchPageRecycleViewAdapter.update(searchList);
        states = false;

    }

    @Override
    public void onRefresh() {
        searchList.clear();
        currentPage = 0;
        if (key == 1)
            httpRequest(keyword, keyname, 1, currentPage + "");
        if (key == 2)
            httpRequest(keyword, keyname, 2, currentPage + "");
        if (key == 3) {
            httpRequest(keyword, keyname, 3, order, currentPage + "");
        }
    }

    /**
     * 有序搜索结果
     */
    @Override
    public void onSearchByOrderSuccess(String success) {
        if (footer != null)
            searchList.remove(footer);
        phareJsonDataforGoodList(success);
    }

    @Override
    public void onSearchByOrderFail(String fail) {

    }


}
